import { initSearchConfig, TableSearchPanel, XxpageContainer, XxTable } from "@/ui";
import React, { useEffect, useRef, useState } from "react";
import getSearchFields from "./config/searchFields";
import getActoinPanel from "./config/action";
import getColumns from "./config/columns";
import EditForm from "./editForm";
import { devApi as api } from "@/api";
import download from "@/service/axios/download";
import { deleteConfirm, successAlert } from "@/common/methods";


/**@description 代码生成 */
const CodeGengeration = () => {
    const searchFormRef = useRef(null); //搜索表单的引用对象，用于获取/操作表单实例
    const editFormRef = useRef(null);
    const [params, setParams] = useState({ ...initSearchConfig(getSearchFields({ searchFormRef })) })
    const [state, setState] = useState({
        data: [],
        totalCount: 0
    })
    const [loading, setLoading] = useState(false);

    //搜索事件
    const onClickSearch = (value) => {
        setParams({
            ...params,
            ...value,
            current: 1,
        });
    };


    /**@description 查找列表 */
    const getList = async () => {
        setLoading(true);
        const { data, code, msg } = await api.queryList({ pageSize: 10, current: 1, ...params });
        setState({
            data: [...data.list],
            totalCount: data.totalCount || 0,
        })
        setLoading(false);

    }

    const onChange = (current, pageSize) => {
        setParams({
            ...params,
            current,
            pageSize
        })
    }
    useEffect(() => {
        getList()
    }, [params])

    /**  @description 打开编辑菜单窗口 */
    const open = ({ type = "add", record = Object }) => {
        editFormRef.current.open({ type, record });
    }

    /**@description 删除按钮操作 */
    const handleDelete = async (object) => {
        try {
            await deleteConfirm();
            const { code, msg } = await api.delete(object.id)
        } catch (error) {

        } finally {
            getList();
        }
    }

    /**@description 下载代码 */
    /**
     * 下载指定记录的代码文件。
     *
     * @async
     * @function downloadCode
     * @param {Object} params - 下载参数对象。
     * @param {string} params.type - 下载类型（当前未使用）。
     * @param {Object} params.record - 包含记录信息的对象。
     * @param {number|string} params.record.id - 要下载代码的记录ID。
     * @returns {Promise<void>} 返回一个 Promise，在代码下载并触发下载操作后解决。
     *
     * @description
     * 该函数通过调用 API 下载指定记录的代码，并以 ZIP 格式触发浏览器下载。
     * 下载完成后，会在控制台输出下载结果。
     */
    const downloadCode = async ({ type, record }) => {
        const res = await api.download(record.id)
        console.log("下载代码结果：", res);
        // download.zip()
        download.zip(res, 'codegen.zip')
    }


    const [selectedKeys, setSelectedKeys] = useState([])
    const onSelectChange = (newSelectedRowKeys, selectedRows) => {
        setSelectedKeys(newSelectedRowKeys);
    }
    const actionPanel = getActoinPanel({
        open: open,

    })
    const tableProps = {
        tablePanelConfig: actionPanel,
        loading,
        columns: getColumns({ open, handleDelete, download: downloadCode }),
        dataSource: state.data,
        pagination: {
            total: state.totalCount,
            pageSize: params.pageSize,
            onChange: onChange,
            current: params.current

        },
        rowSelection: {
            type: "checkbox",
            selectedRowKeys: selectedKeys,
            onChange: onSelectChange,
        },
        rowKey: 'id',
        selectedRowKeys: selectedKeys,
        onRow: (record, index) => {
            return {
                onDoubleClick: () => {

                }
            }
        },
    }


    return (
        <XxpageContainer>
            <EditForm onRef={editFormRef} getList={getList} />
            <TableSearchPanel
                onRef={searchFormRef}
                fields={getSearchFields({ searchFormRef })}
                onSearch={onClickSearch}
            />
            <XxTable  {...tableProps} />

        </XxpageContainer>
    )
}

export default CodeGengeration;